import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/Login/index.vue'
import Layout from '@/views/Layout/index.vue'
import home from '@/views/home'
import question from '@/views/question'
import video from '@/views/video'
import user from '@/views/user'
import search from '@/views/search'
import Article from '@/views/Article'
import searchResult from '@/views/search/searchResult'
import Profile from '@/views/user/Profile.vue'
import chat from '@/views/user/chat.vue'
import store from '@/store'
Vue.use(VueRouter)

// 设置全局前置守卫后，处理重复跳转路由, 或者重定向时, 控制台的红色警告
// 将原型上原始的方法, 存到了一个变量中
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

const router = new VueRouter({
  routes: [
    { path: '/', redirect: '/home' },
    { path: '/login', component: Login },
    {
      path: '/',
      component: Layout,
      children: [
        { path: 'home', component: home },
        { path: 'question', component: question },
        { path: 'video', component: video },
        { path: 'user', component: user }
      ]
    },
    { path: '/search', component: search },
    { path: '/article/:id', component: Article },
    { path: '/searchresult', component: searchResult },
    { path: '/Profile', component: Profile },
    { path: '/chat', component: chat }
  ]
})

// ======= 全局前置守卫 =======
const AuthUrls = ['/user', '/pay', '/cart']
router.beforeEach((to, from, next) => {
  // 优化【必加】：
  // 判断：有token，即已经登录，不需要看到登录页，直接引导到首页
  const token = store.state.user.tokenInfo.token
  if (token && to.path === '/login') {
    router.push('/')
    return
  }
  if (AuthUrls.includes(to.path)) {
    console.log('登录才能访问')

    if (token) {
      next()
    } else {
      next({
        path: '/login',
        query: {
          backto: to.fullPath
        }
      })
    }
  } else {
    console.log('直接访问')
    next()
  }
})

export default router
